package view.conponent;

import com.alibaba.fastjson.JSON;
import model.assessment.Question;
import model.assessment.Template;
import net.ToServer;
import net.passClass.PassQuestion;
import net.passClass.PassTemplate;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Vector;

public class TemplateManager extends Box {
    final int WIDTH = 1080;

    private final JTable table;
    private final Vector<Vector<String>> tableData;
    private final DefaultTableModel tableModel;

    private JTable questionTable;
    private final Vector<Vector<String>> questionTableData;
    private final DefaultTableModel questionTableModel;

    public TemplateManager() {
        //指定垂直布局
        super(BoxLayout.Y_AXIS);

        //组装表格
        String[] ts = {"名称","类型","UID"};
        Vector<String> titles = new Vector<>(Arrays.asList(ts));

        tableData = new Vector<>();

        tableModel = new DefaultTableModel(tableData, titles);
        table = new JTable(tableModel){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);


        JTable tQuestionTable;
        Vector<String> tQuestionTitles;
        Vector<Vector<String>> tQuestionTableData;
        DefaultTableModel tQuestionTableModel;

        String[] tQuestionTs = {"名称","类型","UID"};
        tQuestionTitles = new Vector<>(Arrays.asList(tQuestionTs));

        tQuestionTableData = new Vector<>();

        tQuestionTableModel = new DefaultTableModel(tQuestionTableData, tQuestionTitles);
        tQuestionTable = new JTable(tQuestionTableModel){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tQuestionTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        JScrollPane tQuestionScrollPane = new JScrollPane(tQuestionTable);

        JScrollPane scrollPane = new JScrollPane(table);
        JSplitPane twoTables = new JSplitPane();
        twoTables.setLeftComponent(scrollPane);
        twoTables.setRightComponent(tQuestionScrollPane);
        twoTables.setMinimumSize(new Dimension(870,100));
        twoTables.setContinuousLayout(true);
        twoTables.setDividerSize(8);
        twoTables.setDividerLocation(430);
        JPanel jSplitPane = new JPanel();
        jSplitPane.add(twoTables);
        jSplitPane.setLayout(new GridLayout(1,1));
        jSplitPane.setMinimumSize(new Dimension(870,100));
        this.add(jSplitPane);

        JPanel textFieldPanel = new JPanel();
        textFieldPanel.setMaximumSize(new Dimension(WIDTH, 80));
        textFieldPanel.setMinimumSize(new Dimension(870, 80));
        textFieldPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

        Box box1 = Box.createVerticalBox();
        JTextField name = new JTextField(9);
        JLabel nameStr = new  JLabel("名称");
        box1.add(nameStr);
        box1.add(name);


        Box box2 = Box.createVerticalBox();
        JTextField type = new JTextField(9);
        JLabel typeStr = new  JLabel("类型");
        box2.add(typeStr);
        box2.add(type);


        textFieldPanel.add(box1);
        textFieldPanel.add(box2);
        this.add(textFieldPanel);

        JPanel btnPanel = new JPanel();
        btnPanel.setMaximumSize(new Dimension(870, 80));
        btnPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

        JButton addBtn = new JButton("添加");
        JButton deleteBtn = new JButton("删除");
        JButton updateBtn = new JButton("修改");
        JButton addQuestionBtn = new JButton("添加问题");
        JButton deleteQuestionBtn = new JButton("删除问题");
        JButton getBtn = new JButton("查找");
        JButton refreshBtn = new JButton("刷新");

        addBtn.addActionListener(e -> {
            ToServer.receive("/assessment/template/add",
                    "name:"+name.getText()+"\n" +
                            "type:" +type.getText());
            requestData();
        });

        deleteBtn.addActionListener(e -> {
            int[] selected = table.getSelectedRows();
            for (int num: selected) {
                System.out.println(num);
                ToServer.receive("/assessment/template/delete","uid:"+table.getValueAt(num,2));
            }
            requestData();
        });


        addQuestionBtn.addActionListener(e -> {
            int[] selected = questionTable.getSelectedRows();
            for (int num: selected) {
                ToServer.receive("/assessment/template/addQuestion",
                        "uid:" + table.getValueAt(table.getSelectedRow(),2) + "\n" +
                                "questionUID:" + questionTable.getValueAt(num,5));
            }
            requestData();
            tQuestionTableModel.fireTableDataChanged();
        });

        deleteQuestionBtn.addActionListener(e -> {
            int[] selected = tQuestionTable.getSelectedRows();
            for (int num: selected) {
                System.out.println(num);
                ToServer.receive("/assessment/template/deleteQuestion",
                        "uid:"+table.getValueAt(table.getSelectedRow(),2) + "\n" +
                                "questionUID:"+tQuestionTable.getValueAt(num,2));
            }
            requestData();
            tQuestionTableModel.fireTableDataChanged();
        });

        updateBtn.addActionListener(e -> {

            int selected = table.getSelectedRow();
            ToServer.receive("/assessment/template/update",
                    "name:"+name.getText()+"\n" +
                            "uid:"+table.getValueAt(selected,2)+"\n" +
                            "type:" +type.getText());
            requestData();
        });

        getBtn.addActionListener(e -> {
            PassTemplate receive =(PassTemplate) ToServer.receive("/assessment/template/get",
                    "name:"+name.getText()+"\n" +
                            "type:" +type.getText());
            requestData(receive.getData());
        });

        table.getSelectionModel().addListSelectionListener(e -> {
            int row = table.getSelectedRow();
            if(row != -1) {
                name.setText(table.getValueAt(table.getSelectedRow(),0).toString());
                type.setText(table.getValueAt(table.getSelectedRow(),1).toString());

                Template theTemplate = JSON.parseObject(JSON.toJSONString(((PassTemplate)ToServer.receive("/assessment/template/get",
                        "uid:" + table.getValueAt(row,2))).getData().get(0)),Template.class);

                tQuestionTableData.clear();
                for(String UID: theTemplate.getQuestionUID()){

                    ArrayList<Question> data = ((PassQuestion)ToServer.receive("/assessment/question/get", "uid:"+UID)).getData();

                    if(data!=null) {
                        Question qusetion = JSON.parseObject(JSON.toJSONString(data.get(0)), Question.class);
                        Vector<String> vector = new Vector();
                        vector.add(qusetion.getName());
                        vector.add(qusetion.getType());
                        vector.add(qusetion.getUid());
                        tQuestionTableData.add(vector);
                    }

                }
                tQuestionTableModel.fireTableDataChanged();
            }
        });

        refreshBtn.addActionListener(e -> requestData());

        btnPanel.add(addBtn);
        btnPanel.add(deleteBtn);
        btnPanel.add(updateBtn);
        btnPanel.add(addQuestionBtn);
        btnPanel.add(deleteQuestionBtn);
        btnPanel.add(getBtn);
        btnPanel.add(refreshBtn);
        this.add(btnPanel);

        Box questionFinder = Box.createVerticalBox();


        String[] questionTs = {"名称","类型","答案1","答案2","答案3","UID"};
        Vector<String> questionTitles = new Vector<>(Arrays.asList(questionTs));

        questionTableData = new Vector<>();

        questionTableModel = new DefaultTableModel(questionTableData, questionTitles);
        questionTable = new JTable(questionTableModel){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        questionTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        JScrollPane questionScrollPane = new JScrollPane(questionTable);
        questionFinder.add(questionScrollPane);

        JPanel QtextFieldPanel = new JPanel();
        QtextFieldPanel.setMaximumSize(new Dimension(1200, 80));
        QtextFieldPanel.setMinimumSize(new Dimension(870, 80));
        QtextFieldPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

        Box Qbox1 = Box.createVerticalBox();
        JTextField Qname = new JTextField(9);
        JLabel QnameStr = new  JLabel("名称");
        Qbox1.add(QnameStr);
        Qbox1.add(Qname);


        Box Qbox2 = Box.createVerticalBox();
        JTextField Qtype = new JTextField(9);
        JLabel QtypeStr = new  JLabel("类型");
        Qbox2.add(QtypeStr);
        Qbox2.add(Qtype);

        Box Qbox3 = Box.createVerticalBox();
        JTextField answers_0 = new JTextField(9);
        JLabel answers_0Str = new  JLabel("答案1");
        Qbox3.add(answers_0Str);
        Qbox3.add(answers_0);

        Box Qbox4 = Box.createVerticalBox();
        JTextField answers_1 = new JTextField(9);
        JLabel answers_1Str = new  JLabel("答案2");
        Qbox4.add(answers_1Str);
        Qbox4.add(answers_1);


        Box Qbox5 = Box.createVerticalBox();
        JTextField answers_2 = new JTextField(9);
        JLabel answers_2Str = new  JLabel("答案3");
        Qbox5.add(answers_2Str);
        Qbox5.add(answers_2);


        QtextFieldPanel.add(Qbox1);
        QtextFieldPanel.add(Qbox2);
        QtextFieldPanel.add(Qbox3);
        QtextFieldPanel.add(Qbox4);
        QtextFieldPanel.add(Qbox5);
        questionFinder.add(QtextFieldPanel);

        JPanel QbtnPanel = new JPanel();
        QbtnPanel.setMaximumSize(new Dimension(870, 80));
        QbtnPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

        JButton QgetBtn = new JButton("查找");
        JButton QrefreshBtn = new JButton("刷新");

        QgetBtn.addActionListener(e -> {
            PassQuestion receive =(PassQuestion) ToServer.receive("/assessment/question/get",
                    "name:"+Qname.getText()+"\n" +
                            "type:" +Qtype.getText()+"\n" +
                            "answers_0:" +answers_0.getText()+"\n" +
                            "answers_1:" +answers_1.getText()+"\n" +
                            "answers_2:" +answers_2.getText());
            requestQuestionData(receive.getData());
        });

        questionTable.getSelectionModel().addListSelectionListener(e -> {
            int row = questionTable.getSelectedRow();
            if(row != -1) {
                Qname.setText(questionTable.getValueAt(questionTable.getSelectedRow(),0).toString());
                Qtype.setText(questionTable.getValueAt(questionTable.getSelectedRow(),1).toString());
                answers_0.setText(String.valueOf(questionTable.getValueAt(questionTable.getSelectedRow(),2)));
                answers_1.setText(String.valueOf(questionTable.getValueAt(questionTable.getSelectedRow(),3)));
                answers_2.setText(String.valueOf(questionTable.getValueAt(questionTable.getSelectedRow(),4)));
            }
        });

        QrefreshBtn.addActionListener(e -> requestQuestionData());

        QbtnPanel.add(QgetBtn);
        QbtnPanel.add(QrefreshBtn);
        questionFinder.add(QbtnPanel);

        requestQuestionData();

        this.add(questionFinder);

        requestData();

    }

    public void requestData(){
        ArrayList<Template> data = ((PassTemplate)ToServer.receive("/assessment/template/get","\n")).getData();
        requestData(data);
    }

    public void requestData(ArrayList<Template> data){
        tableData.clear();
        for (int i = 0; i<data.size(); i++) {
            Template qusetion = JSON.parseObject(JSON.toJSONString(data.get(i)),Template.class);
            Vector<String> vector = new Vector();
            vector.add(qusetion.getName());
            vector.add(qusetion.getType());
            vector.add(qusetion.getUid());
            tableData.add(vector);
        }
        tableModel.fireTableDataChanged();

    }

    public void requestQuestionData(){
        ArrayList<Question> data = ((PassQuestion)ToServer.receive("/assessment/question/get","\n")).getData();
        requestQuestionData(data);
    }

    public void requestQuestionData(ArrayList<Question> data){
        questionTableData.clear();
        for(int i = 0; i<data.size(); i++){
            Question qusetion = JSON.parseObject(JSON.toJSONString(data.get(i)),Question.class);
            Vector<String> vector = new Vector();
            vector.add(qusetion.getName());
            vector.add(qusetion.getType());
            vector.add(qusetion.getAnswers_0());
            vector.add(qusetion.getAnswers_1());
            vector.add(qusetion.getAnswers_2());
            vector.add(qusetion.getUid());
            questionTableData.add(vector);
        }
        questionTableModel.fireTableDataChanged();

    }

}
